import { Controller, Post, Body, Get, Param, Delete, UseGuards, UseInterceptors, UploadedFiles } from '@nestjs/common';
import { MaterialsService } from './materials.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/roles.decorator';
import { FilesInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import * as path from 'path';
import { generateUniqueFilename } from '../utils/filename.util';

const uploadPath = path.resolve(__dirname, '../../uploads');

@Controller('materials')
@UseGuards(JwtAuthGuard, RolesGuard)
export class MaterialsController {
  constructor(private readonly materialsService: MaterialsService) {}

  // 创建材料（文字+图片）
  @Post()
  @Roles('ADMIN')
  @UseInterceptors(FilesInterceptor('images', null, {
    storage: diskStorage({
      destination: uploadPath,
      filename: (req, file, cb) => {
        cb(null, generateUniqueFilename(file.originalname));
      },
    })
  }))
  async create(
    @UploadedFiles() files: Express.Multer.File[],
    @Body() createMaterialDto: { content: string; category: string }
  ) {
    const imageUrls = files?.map(file => `/uploads/${file.filename}`) || [];
    return this.materialsService.create({ ...createMaterialDto, imageUrls });
  }

  // 获取单个材料
  @Get(':id')
  async findOne(@Param('id') id: string) {
    return this.materialsService.findOne(id);
  }
  
  
  // 获取所有材料
  @Get()
  async findAll() {
    return this.materialsService.findAll();
  }

  // 删除材料
  @Delete(':id')
  @Roles('ADMIN')
  async remove(@Param('id') id: string) {
    return this.materialsService.remove(id);
  }
}